package com.zbj.validator.controller;

import com.alibaba.fastjson.JSON;
import com.zbj.validator.entity.Student;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.List;

/**
 * @author weigang
 * @create 2017-04-23
 **/
@RestController
public class ValidatorController {

	@RequestMapping("/")
	@ResponseBody
	public String home() {
		return "Hello World!";
	}

	@GetMapping("/validator") // 只支持get方法
//	@PostMapping
	@ResponseBody
	/**
	 * SpringMVC中使用校验方式
	 * 使用 Valid 验证入参，对应的错误参数封装在 BindingResult 对象中，此处已经要记住， BindingResult 紧挨着验证对象
	 * 参数为这样 @Valid Student student, String name, BindingResult result , 就直接抛出如下错误
	 * There was an unexpected error (type=Bad Request, status=400).
	 * Validation failed for object='student'. Error count: 5
	 */
	public String validator(@Valid Student student, BindingResult result){
		if(!ObjectUtils.isEmpty(result)){
			List<ObjectError> errors = result.getAllErrors();
			return JSON.toJSONString(errors);
		}
		return "validator error";
	}

	@RequestMapping("/validatorBoot") // 只支持get方法
	@ResponseBody
	/**
	 * 此方法也是抛出上一个方法的错误，不能正常使用
	 * Spring Boot中使用校验方式
	 */
	public void validatorSpringBoot(@Validated Student student){
	}

}
